<template>
  <div class="pricing-plan-management">
    <a-page-header title="套餐管理" />
    
    <div class="table-actions">
      <a-row :gutter="16">
        <a-col :xs="24" :sm="12" :md="16">
          <a-button type="primary" @click="addNewPlan">
            <template #icon><plus-outlined /></template>
            添加套餐
          </a-button>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8">
          <a-select
            v-model:value="filterStatus"
            placeholder="筛选状态"
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="all">全部套餐</a-select-option>
            <a-select-option value="active">已启用</a-select-option>
            <a-select-option value="inactive">已禁用</a-select-option>
          </a-select>
        </a-col>
      </a-row>
    </div>
    
    <a-table
      :columns="columns"
      :data-source="plans"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.is_active ? 'green' : 'red'">
            {{ record.is_active ? '已启用' : '已禁用' }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'price'">
          <span>¥{{ record.price_monthly.toFixed(2) }}/月</span>
          <br />
          <span>¥{{ record.price_yearly.toFixed(2) }}/年</span>
        </template>
        
        <template v-if="column.key === 'features'">
          <div v-for="(feature, index) in record.features" :key="index">
            <check-circle-outlined style="color: #52c41a; margin-right: 8px;" />
            {{ feature }}
          </div>
        </template>
        
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="editPlan(record)">
              编辑
            </a-button>
            <a-switch
              :checked="record.is_active"
              @change="(checked) => togglePlanStatus(record.id, checked)"
              size="small"
            />
            <a-popconfirm
              title="确定要删除此套餐吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deletePlan(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 编辑套餐对话框 -->
    <a-modal
      :title="isNewPlan ? '添加套餐' : '编辑套餐'"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="modalVisible = false"
      :confirmLoading="confirmLoading"
      width="700px"
    >
      <a-form
        :model="planForm"
        :rules="planFormRules"
        layout="vertical"
        ref="planFormRef"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="套餐名称" name="name">
              <a-input v-model:value="planForm.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="套餐等级" name="tier">
              <a-select v-model:value="planForm.tier">
                <a-select-option value="free">免费版</a-select-option>
                <a-select-option value="basic">基础版</a-select-option>
                <a-select-option value="pro">专业版</a-select-option>
                <a-select-option value="premium">高级版</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="月付价格" name="price_monthly">
              <a-input-number
                v-model:value="planForm.price_monthly"
                :min="0"
                :step="1"
                style="width: 100%"
                addon-before="¥"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="年付价格" name="price_yearly">
              <a-input-number
                v-model:value="planForm.price_yearly"
                :min="0"
                :step="1"
                style="width: 100%"
                addon-before="¥"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="提示词数量限制" name="prompt_limit">
          <a-input-number
            v-model:value="planForm.prompt_limit"
            :min="0"
            :step="1"
            style="width: 100%"
            :formatter="value => value === 0 ? '无限制' : `${value}`"
            :parser="value => value === '无限制' ? 0 : parseInt(value)"
          />
        </a-form-item>
        
        <a-form-item label="套餐描述" name="description">
          <a-textarea v-model:value="planForm.description" :rows="3" />
        </a-form-item>
        
        <a-form-item label="套餐特性" name="features">
          <a-space direction="vertical" style="width: 100%">
            <a-row v-for="(feature, index) in planForm.features" :key="index" :gutter="8">
              <a-col :span="20">
                <a-input v-model:value="planForm.features[index]" placeholder="输入套餐特性" />
              </a-col>
              <a-col :span="4">
                <a-button danger @click="removeFeature(index)">
                  <template #icon><delete-outlined /></template>
                </a-button>
              </a-col>
            </a-row>
            <a-button type="dashed" block @click="addFeature">
              <template #icon><plus-outlined /></template>
              添加特性
            </a-button>
          </a-space>
        </a-form-item>
        
        <a-form-item label="状态" name="is_active">
          <a-switch v-model:checked="planForm.is_active" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined, CheckCircleOutlined } from '@ant-design/icons-vue';

// 定义类型接口



// 假设这些是从API导入的
const getPricingPlans = async (params) => {
  // 模拟API调用
  return {
    results: [
      {
        id: 1,
        name: '免费版',
        tier: 'free',
        description: '适合个人用户的免费套餐',
        price_monthly: 0,
        price_yearly: 0,
        prompt_limit: 10,
        features: ['创建最多10个提示词', '基础AI模型支持', '社区支持'],
        is_active: true
      },
      {
        id: 2,
        name: '基础版',
        tier: 'basic',
        description: '适合初级用户的基础套餐',
        price_monthly: 19.99,
        price_yearly: 199.99,
        prompt_limit: 50,
        features: ['创建最多50个提示词', '所有AI模型支持', '提示词版本管理', '优先电子邮件支持'],
        is_active: true
      },
      {
        id: 3,
        name: '专业版',
        tier: 'pro',
        description: '适合专业用户的高级套餐',
        price_monthly: 49.99,
        price_yearly: 499.99,
        prompt_limit: 200,
        features: ['创建最多200个提示词', '所有AI模型支持', '提示词版本管理', '高级统计分析', '优先技术支持'],
        is_active: true
      },
      {
        id: 4,
        name: '企业版',
        tier: 'premium',
        description: '适合企业用户的顶级套餐',
        price_monthly: 99.99,
        price_yearly: 999.99,
        prompt_limit: 0,
        features: ['无限提示词创建', '所有AI模型支持', '提示词版本管理', '高级统计分析', '专属客户经理', '自定义功能开发'],
        is_active: false
      }
    ],
    count: 4
  };
};

const updatePricingPlan = async (planId, planData) => {
  // 模拟API调用
  console.log('更新套餐:', planId, planData);
  return { ...planData, id: planId };
};

const createPricingPlan = async (planData) => {
  // 模拟API调用
  console.log('创建套餐:', planData);
  return { ...planData, id: Date.now() };
};

const deletePricingPlan = async (planId) => {
  // 模拟API调用
  console.log('删除套餐:', planId);
  return true;
};

const togglePricingPlanStatus = async (planId, status) => {
  // 模拟API调用
  console.log('切换套餐状态:', planId, status);
  return { id: planId, is_active: status };
};

export default {
  name: 'PricingPlanManagement',
  components: {
    PlusOutlined,
    DeleteOutlined,
    CheckCircleOutlined
  },
  setup() {
    const plans = ref([]);
    const loading = ref(false);
    const filterStatus = ref('all');
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100']
    });
    
    const modalVisible = ref(false);
    const confirmLoading = ref(false);
    const isNewPlan = ref(false);
    const planFormRef = ref(null);
    
    const planForm = reactive({
      name: '',
      tier: 'basic',
      description: '',
      price_monthly: 0,
      price_yearly: 0,
      prompt_limit: 0,
      features: [],
      is_active: true
    });
    
    const planFormRules = {
      name: [
        { required: true, message: '请输入套餐名称', trigger: 'blur' }
      ],
      tier: [
        { required: true, message: '请选择套餐等级', trigger: 'change' }
      ],
      price_monthly: [
        { required: true, message: '请输入月付价格', trigger: 'blur' }
      ],
      price_yearly: [
        { required: true, message: '请输入年付价格', trigger: 'blur' }
      ]
    };
    
    const columns = [
      {
        title: '套餐名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '等级',
        dataIndex: 'tier',
        key: 'tier'
      },
      {
        title: '价格',
        key: 'price'
      },
      {
        title: '提示词限制',
        dataIndex: 'prompt_limit',
        key: 'prompt_limit',
        render: (text) => text === 0 ? '无限制' : text
      },
      {
        title: '特性',
        key: 'features'
      },
      {
        title: '状态',
        key: 'status'
      },
      {
        title: '操作',
        key: 'action'
      }
    ];
    
    const fetchPlans = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.current,
          page_size: pagination.pageSize,
          status: filterStatus.value !== 'all' ? filterStatus.value : undefined
        };
        
        const response = await getPricingPlans(params);
        plans.value = response.results;
        pagination.total = response.count;
      } catch (error) {
        message.error('获取套餐列表失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    const handleFilterChange = () => {
      pagination.current = 1;
      fetchPlans();
    };
    
    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchPlans();
    };
    
    const editPlan = (plan) => {
      isNewPlan.value = false;
      planForm.name = plan.name;
      planForm.tier = plan.tier;
      planForm.description = plan.description;
      planForm.price_monthly = plan.price_monthly;
      planForm.price_yearly = plan.price_yearly;
      planForm.prompt_limit = plan.prompt_limit;
      planForm.features = [...plan.features];
      planForm.is_active = plan.is_active;
      
      modalVisible.value = true;
    };
    
    const addNewPlan = () => {
      isNewPlan.value = true;
      planForm.name = '';
      planForm.tier = 'basic';
      planForm.description = '';
      planForm.price_monthly = 0;
      planForm.price_yearly = 0;
      planForm.prompt_limit = 0;
      planForm.features = [''];
      planForm.is_active = true;
      
      modalVisible.value = true;
    };
    
    const handleModalOk = async () => {
      try {
        await planFormRef.value.validate();
        
        confirmLoading.value = true;
        
        // 过滤空特性
        planForm.features = planForm.features.filter(feature => feature.trim() !== '');
        
        if (isNewPlan.value) {
          await createPricingPlan(planForm);
          message.success('套餐创建成功');
        } else {
          await updatePricingPlan(plans.value.find(p => p.name === planForm.name).id, planForm);
          message.success('套餐更新成功');
        }
        
        modalVisible.value = false;
        fetchPlans();
      } catch (error) {
        console.error('表单验证失败:', error);
      } finally {
        confirmLoading.value = false;
      }
    };
    
    const deletePlan = async (planId) => {
      try {
        await deletePricingPlan(planId);
        message.success('套餐删除成功');
        fetchPlans();
      } catch (error) {
        message.error('删除套餐失败');
        console.error(error);
      }
    };
    
    const togglePlanStatus = async (planId, status) => {
      try {
        await togglePricingPlanStatus(planId, status);
        message.success(`套餐${status ? '启用' : '禁用'}成功`);
        fetchPlans();
      } catch (error) {
        message.error(`套餐${status ? '启用' : '禁用'}失败`);
        console.error(error);
      }
    };
    
    const addFeature = () => {
      planForm.features.push('');
    };
    
    const removeFeature = (index) => {
      planForm.features.splice(index, 1);
    };
    
    onMounted(() => {
      fetchPlans();
    });
    
    return {
      plans,
      loading,
      filterStatus,
      pagination,
      columns,
      modalVisible,
      confirmLoading,
      isNewPlan,
      planForm,
      planFormRef,
      planFormRules,
      handleFilterChange,
      handleTableChange,
      editPlan,
      addNewPlan,
      handleModalOk,
      deletePlan,
      togglePlanStatus,
      addFeature,
      removeFeature
    };
  }
};
</script>

<style scoped>
.pricing-plan-management {
  padding: 24px;
}

.table-actions {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pricing-plan-management {
    padding: 12px;
  }
  
  .table-actions {
    margin-bottom: 12px;
  }
  
  .table-actions .ant-row {
    row-gap: 12px;
  }
}

@media (max-width: 576px) {
  .feature-list-item {
    margin-bottom: 8px;
  }
}
</style>